//二叉树最大宽度
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        int ret = 1;
        queue<pair<TreeNode*, long long>> q;
        q.push({root, 0});
        while (q.size()) {
            int n = q.size();
            int base = q.front().second;
            for (int i = 0; i < n; i++) {
                pair<TreeNode*, long> t = q.front();
                q.pop();
                TreeNode* k = t.first;
                long long index = t.second;
                long long currIdx = index - base;
                if (i == n - 1)
                    ret = max(ret, (int)currIdx + 1);
                if (k->left)
                    q.push({k->left, 2 * currIdx + 1});
                if (k->right)
                    q.push({k->right, 2 * currIdx + 2});
            }
        }
        return ret;
    }
};